<template>
  <drag-dialog class="chat-panel" :title="clientChatEn.clientChatName" :width="850" append-to-body
                  :visible.sync="dialogVisible">
    <div class="chat-panel-body">
      <div class="imClientChat-wrapper">
        <chat-room v-if="dialogVisible" ref="imChatBaseRef" :chat-info-en="chatInfoEn" opr-role-name="client" @sendMsg="sendMsg" @chatCallback="chatCallback"></chat-room>
      </div>
      <div class="members-wrapper">
        <group-members></group-members>
      </div>
    </div>
  </drag-dialog>
</template>

<script>
import _ from 'lodash';
import moment from 'moment';
import ChatRoom from './chat/chat-room';
import GroupMembers from './chat/group-members';

export default {
  name: 'chat-panel',
  components: { ChatRoom, GroupMembers },
  data() {
    return {
      dialogVisible: false,
      // 会话信息，包括聊天记录、状态
      chatInfoEn: {
        chatState: 'robot', // chat状态；robot 机器人、agent 客服
        chatName: '', // 当前用户名称
        inputContent: '', // 输入框内容
        msgList: [], // 消息列表
        state: 'on', // 连接状态;on ：在线；off：离线
        lastMsgShowTime: null, // 最后一个消息的显示时间
      },
      // 当前账号的信息
      clientChatEn: {
        clientChatId: '',
        clientChatName: '',
        avatarUrl: require('../images/im_client_avatar.png'),
      },
      // 服务端chat信息
      serverChatEn: {
        serverChatName: '',
        avatarUrl: '',
      },
      // 机器人信息
      robotEn: {
        robotName: '小旺',
        avatarUrl: require('../images/im_robot_avatar.png'),
      },
    };
  },
  methods: {
    /**
     * 打开聊天面板需要传入的对象
     * @param chatInfo
     */
    open(chatInfo) {
      if (!chatInfo) {
        this.$message({ type: 'error', message: '打开聊天面板失败，请稍后重试~~' });
        return;
      }
      console.log('聊天面板 => ', JSON.parse(JSON.stringify(chatInfo)));
      this.dialogVisible = true;
      this.regClientChatEn(chatInfo);
    },

    /**
     * 注册账号信息
     */
    regClientChatEn(chatInfo) {
      this.clientChatEn.clientChatId = chatInfo.id;
      this.clientChatEn.clientChatName = chatInfo.label;

      // 模拟消息
      this.addChatMsg({
        role: 'robot',
        chatName: this.clientChatEn.clientChatName,
        avatarUrl: this.robotEn.avatarUrl,
        contentType: 'transformServer',
      });
    },

    /**
     * 注册socket
     * @param {String} serverChatId 服务端chatId
     */
    regSocket(serverChatId) {
      this.socket = require('socket.io-client')('http://localhost:4001');
      this.socket.on('connect', () => {
        // 客户端上线
        this.socket.emit('CLIENT_ON', {
          clientChatEn: this.clientChatEn,
          serverChatId: serverChatId,
        });

        // 服务端链接
        this.socket.on('SERVER_CONNECTED', data => {
          // 1) 获取客服消息
          this.serverChatEn = data.serverChatEn;

          // 2) 添加消息
          this.addChatMsg({
            role: 'system',
            chatName: '系统消息',
            contentType: 'text',
            content: '客服 ' + data.serverChatEn.serverChatName + ' 为你服务',
          });
        });

        // 接受服务端信息
        this.socket.on('SERVER_SEND_MSG', (data) => {
          data.msg.avatarUrl = this.serverChatEn.avatarUrl;
          this.addChatMsg(data.msg, () => {
            this.$refs.imChatBaseRef.goEnd();
          });
        });

        // 离开
        window.addEventListener('beforeunload', () => {
          this.closeChat();
        });
      });
    },

    /**
     * 结束会话
     */
    closeChat() {
      if (this.chatInfoEn.chatState === 'agent') {
        this.socket.emit('CLIENT_OFF', {
          clientChatEn: this.clientChatEn,
          serverChatId: this.serverChatEn.serverChatId,
        });
        this.socket.close();
        this.chatInfoEn.state = 'off';
      }
    },

    /**
     * 添加chat对象的msg
     * @param {Object} msg 消息对象；eg：{role:'system',content:'含有新的消息'}
     * @param {String} msg.role 消息所有者身份；eg：'system'系统消息；
     * @param {String} msg.contentType 消息类型；text:文本(默认)；image:图片
     * @param {String} msg.content 消息内容
     * @param {Function} successCallback 添加消息后的回调
     */
    addChatMsg(msg, successCallback) {
      // 1. 设定默认值
      msg.role = msg.role === undefined ? 'system' : msg.role;
      msg.contentType = msg.contentType === undefined ? 'text' : msg.contentType;
      msg.createTime = msg.createTime === undefined ? new Date() : msg.createTime;

      const msgList = this.chatInfoEn.msgList ? this.chatInfoEn.msgList : [];

      // 2.插入消息
      // 1)插入日期
      // 实际场景中，在消息上方是否显示时间是由后台传递给前台的消息中附加上的，可参考 微信Web版
      // 此处进行手动设置，5分钟之内的消息，只显示一次消息
      msg.createTime = new Date(msg.createTime);
      if (this.$data.chatInfoEn.lastMsgShowTime == null || msg.createTime.getTime() - this.$data.chatInfoEn.lastMsgShowTime.getTime() > 1000 * 60 * 5) {
        msgList.push({
          role: 'system',
          contentType: 'text',
          content: moment(msg.createTime).format('YYYY-MM-DD HH:mm:ss'),
        });
        this.$data.chatInfoEn.lastMsgShowTime = msg.createTime;
      }
      // 2)插入消息
      msgList.push(msg);

      // 3.设置chat对象相关属性
      this.chatInfoEn.msgList = msgList;

      // 4.回调
      successCallback && successCallback();
    },

    /**
     * 发送消息
     * @param {Object} rs 回调对象
     */
    sendMsg(rs) {
      console.log('send message => ', rs);

      const msg = rs.msg;
      msg.role = 'client';
      msg.chatName = this.clientChatEn.clientChatName;
      msg.avatarUrl = this.clientChatEn.avatarUrl;
      if (this.chatInfoEn.chatState === 'robot') {
        // 机器人发送接口
      } else if (this.chatInfoEn.chatState === 'agent') {
        // 客服接口
        this.socket.emit('CLIENT_SEND_MSG', {
          serverChatId: this.serverChatEn.serverChatId,
          clientChatEn: this.clientChatEn,
          msg,
        });
      }
      // 2.添加到消息集合李
      this.addChatMsg(msg, () => {
        this.$refs.imChatBaseRef.goEnd();
      });
    },

    /**
     * chat回调
     */
    chatCallback(emitType, data) {
      this.$emit('chatCallback', {
        eventType: emitType,
        data: data,
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.chat-panel {
  z-index: 9999 !important;
  right: 320px;

  .chat-panel-body {
    width: 100%;
    height: 500px;
    overflow: hidden;

    &:before, &:after {
      content: '';
      display: table;
      clear: both;
    }

    .imClientChat-wrapper {
      float: left;
      width: 550px;
      height: 100%;
      padding-right: 6px;
    }

    .members-wrapper {
      float: left;
      width: calc(100% - 550px);
      padding-right: 24px;
      height: 100%;
    }
  }
}
</style>
